package com.situ.personal.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.personal.dao.impl.UserDaoImpl;
import com.situ.personal.entity.Department;
import com.situ.personal.entity.PageInfo;
import com.situ.personal.entity.User;
import com.situ.personal.service.IDepartmentService;
import com.situ.personal.service.IUserService;
import com.situ.personal.service.impl.DepartmentServiceImpl;
import com.situ.personal.service.impl.UserServiceImpl;
import com.situ.personal.util.JDBCUtil;
import com.situ.personal.util.JSONResult;
import com.situ.personal.util.JSONUtil;
import com.situ.personal.vo.UserDeptVO;

@WebServlet("/user")
public class UserServlet extends HttpServlet{
	private IUserService userService = new UserServiceImpl();
	private IDepartmentService departmentService = new DepartmentServiceImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// http://localhost:8080/Java2012WebPersonal/user?method=selectAll
		req.setCharacterEncoding("UTF-8");
		
		
		String method = req.getParameter("method");
		switch (method) {
		case "selectAll":
			selectAll(req, resp);
			break;
		case "selectByPage":
			selectByPage(req, resp);
			break;
		case "deleteById":
			deleteById(req, resp);
			break;
		case "getUserInsertPage":
			getUserInsertPage(req, resp);
			break;
		case "insert":
			insert(req, resp);
			break;
		case "getUserUpdatePage":
			getUserUpdatePage(req, resp);
			break;
		case "update":
			update(req, resp);
			break;
		case "selectUserDeptInfo":
			selectUserDeptInfo(req, resp);
			break;
		case "login":
			login(req, resp);
			break;
		case "logout":
			logout(req, resp);
		default:
			System.out.println("default method: " + method);
			break;
		}
	}


	private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("UserServlet.logout()");
		HttpSession session = req.getSession();
		session.removeAttribute("user");
		
		resp.sendRedirect(req.getContextPath() + "/login.jsp");
	}


	private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("UserServlet.login()");
		String checkCode = req.getParameter("checkCode");
		HttpSession session = req.getSession();
		String checkCodeInSession = (String) session.getAttribute("checkCodeInSession");
		if (checkCode.equals(checkCodeInSession) == false) {
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}
		
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		User user = userService.login(name, password);
		if (user != null) {
			session.setAttribute("user", user);
			resp.sendRedirect(req.getContextPath() + "/");
		} else {
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
		}
	}


	private void selectUserDeptInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("UserServlet.selectUserDeptInfo()");
		List<UserDeptVO> list = userService.selectUserDeptInfo();
		req.setAttribute("list", list);
		req.getRequestDispatcher("/user_dept_list.jsp").forward(req, resp);
	}


	private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("UserServlet.update()");
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		String age = req.getParameter("age");
		String email = req.getParameter("email");
		String departmentId = req.getParameter("departmentId");
		User user = new User(Integer.parseInt(id), name, password, Integer.parseInt(age), email, Integer.parseInt(departmentId));
		
		userService.update(user);
		
		resp.sendRedirect(req.getContextPath() + "/user?method=selectByPage");
	}


	private void getUserUpdatePage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("UserServlet.getUserUpdatePage()");
		String id = req.getParameter("id");
		User user = userService.selectById(Integer.parseInt(id));
		
		List<Department> list = departmentService.selectAll();
		
		req.setAttribute("user", user);
		req.setAttribute("list", list);
		req.getRequestDispatcher("/user_update.jsp").forward(req, resp);
	}


	private void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("UserServlet.insert()");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String password = req.getParameter("password");
		String email = req.getParameter("email");
		String departmentId = req.getParameter("departmentId");
		User user = new User(name, password, Integer.parseInt(age), email, Integer.parseInt(departmentId));
		
		boolean result = userService.insert(user);
		
		//resp.sendRedirect(req.getContextPath() + "/user?method=selectByPage");
		
		JSONUtil.obj2Json(JSONResult.ok("添加成功"), resp);
	}

	private void getUserInsertPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Department> list = departmentService.selectAll();
		req.setAttribute("list", list);
		req.getRequestDispatcher("/user_insert.jsp").forward(req, resp);
	}

	private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("UserServlet.deleteById()");
		String id = req.getParameter("id");
		userService.deleteById(Integer.parseInt(id));
		
		// resp.sendRedirect(req.getContextPath() + "/user?method=selectByPage");
		
		// {isSuccess : true}
		// Map<String, Boolean> map = new HashMap<String, Boolean>();
		// map.put("isSuccess", true);
		// JSONUtil.obj2Json(map, resp);
		
		// JSONResult jsonResult = new JSONResult(JSONResult.OK, "删除成功");
		// JSONUtil.obj2Json(jsonResult, resp);
		
		JSONUtil.obj2Json(JSONResult.ok("删除成功"), resp);
		
		// 对于删除失败，会抛出异常，后面在Spring中捕获全局的异常信息，返回JSONResult.error
	}

	private void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("UserServlet.selectByPage()");
		// /Java2012WebPersonal3/user?method=selectByPage&pageNo=2&pageSize=3
		String pageNoStr = req.getParameter("pageNo");
		String pageSizeStr = req.getParameter("pageSize");
		if (pageNoStr == null || "".equals(pageNoStr)) {
			pageNoStr = "1";
		}
		if (pageSizeStr == null || "".equals(pageSizeStr)) {
			pageSizeStr = "3";
		}
		int pageNo = Integer.parseInt(pageNoStr);
		int pageSize = Integer.parseInt(pageSizeStr);
		
		// 封装PageInfo要交给Service层完成
		PageInfo<User> pageInfo = userService.selectByPage(pageNo, pageSize);
		
		req.setAttribute("pageInfo", pageInfo);
		req.getRequestDispatcher("/user_list.jsp").forward(req, resp);
	}

	private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("UserServlet.selectAll()");
		List<User> list = userService.selectAll();
		
		req.setAttribute("list", list);
		req.getRequestDispatcher("/user_list.jsp").forward(req, resp);
	}

	
	
	
	
}
